package com.sunday.shoufen.ui.widgets;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.PixUtils;
import com.sunday.common.utils.TimeCount;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.entity.Fans;
import com.sunday.shoufen.http.ApiClient;
import com.sunday.shoufen.ui.SearchMemberActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.shoufen.base.Constants.CODE_1;
import static com.sunday.shoufen.base.Constants.SEND_CODE_SIGN;

/**
 * Created by 刘涛 on 2017/11/16.
 */

public class AddMemberWindow extends PopupWindow {


    @Bind(R.id.user_logo)
    CircleImageView userLogo;
    @Bind(R.id.user_name)
    TextView userName;
    @Bind(R.id.user_mobile)
    TextView userMobile;
    @Bind(R.id.cancel)
    TextView cancel;
    @Bind(R.id.confirm)
    TextView confirm;
    @Bind(R.id.edit_code)
    ClearEditText editCode;
    @Bind(R.id.send_code)
    TextView sendCode;
    @Bind(R.id.ll_send_code)
    LinearLayout llSendCode;

    private Context mContext;
    private Fans fans;


    public AddMemberWindow(Context context, Fans fans) {
        this.mContext = context;
        this.fans = fans;
        View windowView = LayoutInflater.from(mContext).inflate(R.layout.layout_add_fans, null);
        int appWidth = DeviceUtils.getDisplay(mContext).widthPixels- PixUtils.dip2px(mContext,40);
        setContentView(windowView);
        ButterKnife.bind(this, windowView);
        llSendCode.setVisibility(View.VISIBLE);
        this.setWidth(appWidth);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setOutsideTouchable(true);
        this.setFocusable(true);
        this.setOnDismissListener(new PoponDismissListener());
        this.setBackgroundDrawable(new BitmapDrawable());
        //this.setAnimationStyle(R.style.popuwindow);
        initView();
    }

    private void initView() {
        if (fans == null) {
            return;
        }
        Glide.with(mContext)
                .load(fans.getLogo())
                .error(R.mipmap.ic_default)
                .into(userLogo);
        userName.setText(fans.getNickName()==null?"收分了用户":fans.getNickName());
        userMobile.setText(fans.getMobile());
    }


    //显示
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            this.showAtLocation(parent, Gravity.CENTER, 0, 0);
            backgroundAlpha(0.5f);
        } else {
            this.dismiss();
        }
    }


    private String code;

    @OnClick({R.id.cancel, R.id.confirm, R.id.send_code})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                dismiss();
                break;
            case R.id.confirm:
                code = editCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showToast(mContext, "请输入验证码");
                    return;
                }
                addMember();
                break;
            case R.id.send_code:
                sendCode();
                break;
        }
    }

    private TimeCount timeCount;

    private void sendCode() {
        timeCount = new TimeCount(60000, 1000, sendCode);
        ((SearchMemberActivity) mContext).showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().sendCode(fans.getMobile(), SEND_CODE_SIGN, CODE_1, 5);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null) {
                    return;
                }
                ((SearchMemberActivity) mContext).dissMissDialog();
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "验证码已发送到该会员手机");
                    timeCount.start();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ((SearchMemberActivity) mContext).dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void addMember() {
        ((SearchMemberActivity) mContext).showLoadingDialog(0);
        Call<ResultDO> call1 = ApiClient.getApiAdapter().addMember(BaseApp.getInstance().getMember().getId(), fans.getMobile(), code);
        call1.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (response.body() == null) {
                    return;
                }
                ((SearchMemberActivity) mContext).dissMissDialog();
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "添加成功");
                    dismiss();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ((SearchMemberActivity) mContext).dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    /**
     * 弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class PoponDismissListener implements OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
            dismiss();
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) mContext).getWindow().setAttributes(lp);
    }

    @Override
    public void dismiss() {
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.dismiss();
    }
}